#include "family.h"
#include <queue>
#include <iomanip>

// 显示第几代
void FamilyTree::displayNthGeneration(int n)
{
    if (root == nullptr)
    {
        std::cout << "家谱为空。" << std::endl;
        return;
    }

    std::queue<FamilyMember *> q;
    q.push(root);
    int currentGeneration = 0;

    while (!q.empty())
    {
        int levelSize = q.size(); // 当前代数的节点数

        if (currentGeneration == n)
        {
            for (int i = 0; i < levelSize; ++i)
            {
                FamilyMember *member = q.front();
                q.pop();
                std::cout << "姓名: " << member->name << ", 出生日期: " << member->birthDate << ", 联系信息: " << member->contactInfo << std::endl;
            }
            return; // 显示完第n代后停止
        }

        for (int i = 0; i < levelSize; ++i)
        {
            FamilyMember *member = q.front();
            q.pop();
            for (auto child : member->children)
            {
                q.push(child);
            }
        }

        currentGeneration++;
    }

    std::cout << "家谱中不存在第 " << n << " 代。" << std::endl;
}

// 显示家谱图
void FamilyTree::displayTree()
{
    if (root == nullptr)
    {
        std::cout << "家谱为空。" << std::endl;
        return;
    }

    std::queue<FamilyMember *> q;
    q.push(root);
    int currentGeneration = 1;

    while (!q.empty())
    {
        int levelSize = q.size();                                    // 当前层的节点数
        int maxLevelSize = 1 << (currentGeneration - 1);             // 当前层最大可能的节点数
        int totalWidth = 80;                                         // 设定总宽度
        int space = (totalWidth - levelSize * 10) / (levelSize + 1); // 计算每个节点之间的空格数

        std::cout << "第 " << currentGeneration << " 代：";
        for (int i = 0; i < levelSize; ++i)
        {
            FamilyMember *member = q.front();
            q.pop();

            // 为第一个节点前添加空格以居中显示
            if (i == 0)
            {
                std::cout << std::setw(space + 10) << member->name;
            }
            else
            {
                std::cout << std::setw(space * 2 + 10) << member->name;
            }

            for (auto child : member->children)
            {
                q.push(child); // 将子节点加入队列
            }
        }
        std::cout << std::endl;
        currentGeneration++;
    }
}